from google.appengine.ext import db
from google.appengine.api import memcache
from domain import article
from repository import baserepository

class ArticleRepository(baserepository.BaseRepository):

    def __init__(self):
        self._has_next = False
        self._has_prev = False

    def hasNext(self):
        return self._has_next
    
    def hasPrev(self):
        return self._has_prev

    def getAll(self):
        articles = db.GqlQuery("SELECT * FROM Article ORDER BY date DESC")
        return articles

    def getAllByRange(self, page, items_per_page):
        query = db.GqlQuery("SELECT * FROM Article ORDER BY date DESC")
        articles = query.fetch(items_per_page, offset=(page * items_per_page))
        next = query.fetch(1, (page * items_per_page) + len(articles))
        if next:
            self._has_next = True
        if page > 0:
            self._has_prev = True
        return articles

    def searchByRange(self, start, howmany, searchterm):
        query = db.GqlQuery("SELECT * FROM Article WHERE title like :1 OR summary like :2 ORDER BY date DESC", searchterm, searchterm)
        articles = query.fetch(howmany, offset=start)
        return articles


    def getRange(self, page, items_per_page, category=None):
        if (category == None):
            query = db.GqlQuery("SELECT * FROM Article WHERE published=True ORDER BY date DESC")
        else:
            query = db.GqlQuery("SELECT * FROM Article WHERE published=True AND categories = :1 ORDER BY date DESC", category)
        articles = query.fetch(items_per_page, offset=(page * items_per_page))
        next = query.fetch(1, (page * items_per_page) + len(articles))
        if next:
            self._has_next = True
        if page > 0:
            self._has_prev = True
        return articles

    def getNewest(self, howmany):
        query = db.GqlQuery("SELECT * FROM Article WHERE published=True and mainfeature=False ORDER BY date DESC")
        articles = query.fetch(howmany)
        return articles

    def getMainFeature(self):
        query = db.GqlQuery("SELECT * FROM Article WHERE published=True AND mainfeature=True ORDER BY date DESC")
        articles = query.fetch(1)
        return articles

    def getByKey(self, articlekey):
        return super(ArticleRepository, self).getByKey(articlekey, article.Article)

    def getByTitlePath(self, titlepath):
        query = db.GqlQuery("SELECT * FROM Article WHERE titleurlpath = :1", titlepath)
        thearticle = query.fetch(1)
        return thearticle

    def save(self, newarticle):
        newarticle.setTitleUrlPath()
        return super(ArticleRepository, self).save(newarticle, article.Article)

    def delete(self, oldarticle):
        super(ArticleRepository, self).delete(oldarticle, article.Article)


